package org.jxkj.service;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.jxkj.client.PmuClient;
import org.jxkj.config.MysqlConfig;
import org.jxkj.dto.PmuPointDataDTO;
import org.jxkj.utils.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

public class PmuSwitchService {

    public static void calcAndSaveFreq(Dataset<Row> list) throws InterruptedException, SQLException {
        List<CalcData> calcList = new ArrayList<>();
        List<Row> rows = list.collectAsList();
        for (Row row : rows) {
            CalcData data = new CalcData();
            data.setFrequencyId(row.getString(0));
            data.setActPointCode(row.getString(1));
            data.setPointName(row.getString(2));
            data.setFreqPointCode(row.getString(3));
            data.setStartTime(row.getLong(4));
            data.setEndTime(row.getLong(5));
            calcList.add(data);
        }

        if (CollectionUtils.isEmpty(calcList)) {
            return;
        }

        // 数据库属性
        Properties prop = new Properties();
        prop.setProperty("user", MysqlConfig.user2);
        prop.setProperty("password",MysqlConfig.password2);
        prop.setProperty("driver",MysqlConfig.driver2);
        prop.setProperty("charset","UTF-8");

        for (CalcData calcData : calcList) {
            String id = calcData.getFrequencyId();
            String freqPointCode = calcData.getFreqPointCode();
            Long startTime = calcData.getStartTime();
            Long endTime = calcData.getEndTime();
            // 查询频率数据
            PmuPointDataDTO dto = PmuClient.getMillisData(freqPointCode, startTime, endTime);
            Thread.sleep(200);
            if (dto == null || StringUtils.isBlank(dto.getPointCode()) || MapUtils.isEmpty(dto.getData())) {
                continue;
            }

            // 找出最大频率，最小频率，是否越限
            Collection<Double> values = dto.getData().values();
            Double maxFreq = PmuClient.round(PmuClient.max(values), 4);
            Double minFreq = PmuClient.round(PmuClient.min(values), 4);
            String overFreq = "否";
            if (maxFreq > 50.0 + 0.05 || minFreq < 50.0 - 0.05) {
                overFreq = "是";
            }

            // 更新数据库
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                Class.forName(MysqlConfig.driver2);
                conn = DriverManager.getConnection(MysqlConfig.url2, prop);
                String sql = new StringBuilder()
                        .append(" update hms_cm_high_frequency")
                        .append(" set max_freq = ?, min_freq = ?, over_freq = ?")
                        .append(" where frequency_id = ?").toString();
                ps = conn.prepareStatement(sql);

                ps.setDouble(1, maxFreq);
                ps.setDouble(2, minFreq);
                ps.setString(3, overFreq);
                ps.setString(4, id);
                ps.executeUpdate();
                System.out.println("更新数据完毕, frequency_id = " + id);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            Thread.sleep(200);
        }

    }

    @Data
    private static class CalcData {
        private String frequencyId;
        private String actPointCode;
        private String pointName;
        private String freqPointCode;
        private Long startTime;
        private Long endTime;
    }
}
